package com.smart4j.chapter.modules.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.smart4j.chapter.modules.entity.Client;
import com.smart4j.chapter.modules.service.ClientService;
import com.smart4j.chapter.modules.service.impl.ClientServiceImpl;

/**
 * json 输出servlet 
 */
@WebServlet("/jsonServlet")
public class JsonServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private ClientService<Client> clientService = new ClientServiceImpl();

    /**
     * @see HttpServlet#HttpServlet()
     */
    public JsonServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 解决json中文乱码 
		response.setContentType("text/json;charset=UTF-8");
		PrintWriter out = response.getWriter();
		List<Client> list = clientService.findList(new Client());
		Gson gson = new Gson();
		String json = gson.toJson(list);
		out.println(json);
		out.flush();
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
